<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item >用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 间距 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 查询用户 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryIofo.query"
            clearable
            @clear="getUsersList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe>
        <!-- 添加索引 -->
        <!-- 添加#有这个会让表格没对齐 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- 插槽666 -->
            <!-- 获取插槽的内容 -->
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="ShowEidtDialogVisible(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserByid(scope.row.id)"
            ></el-button>
            <!-- 分配权限 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              class="waring-ziti"
              :enterable="false"
            >
              <!--  circle为圆形 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRightdVisible(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryIofo.pagenum"
        :page-sizes="[1, 2, 6, 10]"
        :page-size="queryIofo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户提示框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addFromClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editFromClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
        status-icon
      >
        <!--disabled只读  -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editNewUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRightsdialogVisible"
      width="50%"
    >
      <div>
        <p>当前用户：{{userinfo.username}}</p>
        <p>当前角色：{{userinfo.role_name}}</p>
        <p>
          分配新角色：
          <!-- 通过v-model传需要的值 value-->
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleUsers">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 用法就是放在data之下
    // 自定义验证邮箱
    var checkEmail = (rule, value, callback) => {
      // 正则表达式
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义验证手机号
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[345789]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取用户列表参数
      queryIofo: {
        // 搜索参数
        query: '',
        // 当前页码
        pagenum: 1,
        // 页面数据条数
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加用户提示框的显示状态
      addDialogVisible: false,
      // 修改用户提示框的显示状态
      editDialogVisible: false,
      // 分配角色提示框的显示状态
      setRightsdialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单数据
      editForm: {},
      // 当前需要被分配角色的用户
      userinfo: {},
      // 分配角色数据
      roleList: [],
      // 已选中的角色Id值
      selectRoleId: '',
      // 添加用户验证规则
      addFormRules: {
        // 验证用户名
        username: [
          {
            required: true,
            message: '请输入用户账号',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        // 验证密码是否合法
        password: [
          {
            required: true,
            message: '请输入登录密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 20,
            message: '长度在 6到 20 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    // 页面一创建就访问数据
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryIofo
      })
      if (res.meta.status !== 200) { return this.$message.error('获取用户列表失败') }
      this.$message.success('获取用户列表成功')
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(this.userList);
    },
    // 监听页面数改变事件
    handleSizeChange (newSize) {
      // 重新获取页面数据
      this.queryIofo.pagesize = newSize
      this.getUsersList()
    },
    // 监听页码改变事件
    handleCurrentChange (newPage) {
      this.queryIofo.pagenum = newPage
      this.getUsersList()
    },
    // 状态改变事件
    async userStateChange (userifon) {
      const { data: res } = await this.$http.put(
        `users/${userifon.id}/state/${userifon.mg_state}`
      )
      if (res.meta.status !== 200) {
        //  重置为没有修改状态
        userifon.mg_state = !userifon.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    addFromClose () {
      // 给获取的实例对象添加一个重置的方法
      this.$refs.addFormRef.resetFields()
    },
    // 添加的预验证
    addNewUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        // console.log(res);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加用户成功')
        //  隐藏对话框
        this.addDialogVisible = false
        this.getUsersList()
      })
    },
    // 根据id查询值
    // product_id还是用户的id
    async ShowEidtDialogVisible (productId) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${productId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      // console.log(res);
      // console.log(product_id);
    },
    editFromClose () {
      // 给获取的实例对象添加一个重置的方法
      this.$refs.editFormRef.resetFields()
    },
    // 修改的预验证
    editNewUser () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改用户成功')
        this.editDialogVisible = false
        this.getUsersList()
      })
    },
    // 删除提示
    async removeUserByid (userid) {
      //  console.log(userid)
      const conformResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // console.log(conformResult)
      // 如果用户确认删除就是返回字符串confirm
      // 如果用户取消删除返回cancel
      if (conformResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { data: res } = await this.$http.delete(`users/${userid}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      // 保留当前页
      this.getUsersList()
    },
    // 分配角色
    async setRightdVisible (userinfo) {
      this.userinfo = userinfo
      // console.log(this.userinfo);
      // 展示对话框之前，获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
      this.setRightsdialogVisible = true
    },
    // 确认分配角色
    async  saveRoleUsers () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择分配角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) { return this.$message.error('分配角色失败') }
      this.$message.success('分配角色成功')
      // 保留当前页
      this.getUsersList()
      this.setRightsdialogVisible = false
    }
  }
}
</script>
<style Lang="less" scoped>
.waring-ziti {
  font-size: 12px;
}
</style>
